<template>
  <canvas id="timeSeriesChart"></canvas>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed, nextTick } from 'vue'
import Chart from 'chart.js/auto' // 导入Chart.js
import 'chartjs-plugin-annotation' // 导入标注插件

const props = defineProps({
  device: String, // 从父组件 RightPanel 接收当前选中的设备名称
})

let myChart = null // 用于存储Chart实例

// 定义工艺参数的警戒线和注意线（可以根据不同点位进行调整）
const THRESHOLDS = {
  FIC1002D: {
    // 联醇装置的点位
    caution: 60,
    alert: 58,
  },
  FI615: {
    // 解吸浓缩系统装置的点位
    caution: 65,
    alert: 62,
  },
}

// 根据当前设备选择对应的点位名称
const getPointNameForDevice = (device) => {
  if (device === '联醇装置') {
    return 'FIC1002D'
  } else if (device === '解吸浓缩系统装置') {
    return 'FI615'
  }
  return '' // 如果 device 不匹配，返回空字符串
}

/**
 * 销毁 Chart.js 实例，释放资源。
 * 此函数放在 drawMainEvaluationChart 和 watch 之前定义，确保其在作用域内可见。
 */
const destroyChart = () => {
  if (myChart) {
    myChart.destroy()
    myChart = null
    console.log(`MainEvaluationChart: Chart instance destroyed.`)
  }
}

/**
 * 生成模拟的时间序列数据。
 * @param {string} pointName - 点位名称，用于模拟不同数据。
 * @param {number} numPoints - 生成的数据点数量。
 * @returns {Object} 包含 labels 和 data 的模拟数据。
 */
const generateMockEvaluationData = (pointName, numPoints = 50) => {
  const labels = []
  const data = []
  let baseValue
  let fluctuationRange

  if (pointName === 'FIC1002D') {
    baseValue = 55
    fluctuationRange = 8
  } else if (pointName === 'FI615') {
    baseValue = 68
    fluctuationRange = 6
  } else {
    baseValue = 50
    fluctuationRange = 10
  }

  let currentValue = baseValue + (Math.random() - 0.5) * fluctuationRange

  for (let i = 0; i < numPoints; i++) {
    const date = new Date(Date.now() - (numPoints - 1 - i) * 30 * 1000) // 每30秒一个点
    labels.push(
      date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }),
    )

    currentValue += (Math.random() - 0.5) * (fluctuationRange / 5) // 小幅波动
    currentValue = Math.max(
      baseValue - fluctuationRange / 2,
      Math.min(baseValue + fluctuationRange / 2, currentValue),
    ) // 限制在一定范围内
    data.push(parseFloat(currentValue.toFixed(4)))
  }
  return { labels, data }
}

// 从后端获取工艺运行状态评估数据，如果失败则使用模拟数据
const fetchEvaluationData = async (pointName) => {
  if (!pointName) {
    console.warn('MainEvaluationChart: Point name is empty, returning empty data.')
    return { labels: [], data: [] }
  }

  try {
    console.log(
      `MainEvaluationChart: Attempting to fetch evaluation data for point: ${pointName} from backend.`,
    )
    const response = await fetch(`/api/get_latest_point_data?point=${pointName}`)

    if (!response.ok) {
      // 如果后端接口不可用或返回非2xx状态码，抛出错误
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const result = await response.json()

    if (!result.success) {
      // 如果后端返回 success: false，也视为错误
      throw new Error(
        `API returned success: false for ${pointName} - ${result.message || 'Unknown error'}`,
      )
    }

    const labels = result.data.map((item) => {
      return new Date(item.datetime).toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      })
    })
    const dataValues = result.data.map((item) => item.value)

    console.log(`MainEvaluationChart: Successfully loaded data for ${pointName} from backend.`)
    return { labels, data: dataValues }
  } catch (error) {
    console.error(
      `MainEvaluationChart: Error fetching evaluation data for ${pointName} from backend, using mock data:`,
      error,
    )
    // 使用模拟数据作为 fallback
    return generateMockEvaluationData(pointName)
  }
}

const drawMainEvaluationChart = async () => {
  destroyChart() // 在绘制新图表前销毁旧图表实例

  const pointName = getPointNameForDevice(props.device) // 获取当前设备对应的点位名称
  const { labels, data } = await fetchEvaluationData(pointName) // 获取数据

  const canvasElement = document.getElementById('timeSeriesChart')
  if (!canvasElement) {
    console.error(
      "MainEvaluationChart: Canvas element 'timeSeriesChart' not found. Cannot draw chart.",
    )
    return
  }
  const ctx = canvasElement.getContext('2d')
  if (!ctx) {
    console.error('MainEvaluationChart: Could not get 2D context for canvas.')
    return
  }

  if (labels.length === 0) {
    console.warn(
      `MainEvaluationChart: No data to display for main evaluation chart (${pointName}).`,
    )
    // 清空 canvas 并显示“暂无数据”提示
    ctx.clearRect(0, 0, canvasElement.width, canvasElement.height)
    ctx.font = '16px Arial'
    ctx.fillStyle = '#888'
    ctx.textAlign = 'center'
    ctx.fillText('暂无数据', canvasElement.width / 2, canvasElement.height / 2)
    return
  }

  const currentThresholds = THRESHOLDS[pointName] || { caution: null, alert: null }

  // 动态计算Y轴的最小值和最大值，考虑数据和阈值线
  const allNumericalData = [...data]
  if (currentThresholds.alert !== null) allNumericalData.push(currentThresholds.alert)
  if (currentThresholds.caution !== null) allNumericalData.push(currentThresholds.caution)

  let minValue = allNumericalData.length > 0 ? Math.min(...allNumericalData) : 0
  let maxValue = allNumericalData.length > 0 ? Math.max(...allNumericalData) : 100

  if (minValue === maxValue) {
    // 避免 min/max 相同导致图表绘制问题
    minValue -= 5
    maxValue += 5
  }
  const padding = (maxValue - minValue) * 0.1

  myChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [
        {
          label: `工艺参数 (点位: ${pointName})`,
          data: data,
          borderColor: 'rgb(139, 69, 19)',
          backgroundColor: 'rgba(139, 69, 19, 0.1)',
          borderWidth: 2,
          tension: 0.3,
          pointRadius: 0,
          fill: false,
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        title: {
          display: true,
          text: `工艺运行状态评估 - ${pointName}`,
          font: { size: 16 },
        },
        legend: {
          display: false,
        },
        annotation: {
          annotations: {
            cautionLine:
              currentThresholds.caution !== null
                ? {
                    type: 'line',
                    yMin: currentThresholds.caution,
                    yMax: currentThresholds.caution,
                    borderColor: 'rgb(218, 165, 32)',
                    borderWidth: 2,
                    borderDash: [5, 5],
                    label: {
                      enabled: true,
                      content: '注意',
                      position: 'end',
                      backgroundColor: 'rgba(218, 165, 32, 0.8)',
                      color: 'white',
                      font: { size: 10 },
                    },
                  }
                : {},
            alertLine:
              currentThresholds.alert !== null
                ? {
                    type: 'line',
                    yMin: currentThresholds.alert,
                    yMax: currentThresholds.alert,
                    borderColor: 'rgb(220, 53, 69)',
                    borderWidth: 2,
                    borderDash: [5, 5],
                    label: {
                      enabled: true,
                      content: '警戒',
                      position: 'end',
                      backgroundColor: 'rgba(220, 53, 69, 0.8)',
                      color: 'white',
                      font: { size: 10 },
                    },
                  }
                : {},
          },
        },
      },
      scales: {
        x: {
          display: true,
          title: {
            display: true,
            text: '时间',
          },
          ticks: {
            autoSkip: true,
            maxTicksLimit: 10,
          },
        },
        y: {
          display: true,
          title: {
            display: true,
            text: '参数值',
          },
          min: minValue - padding,
          max: maxValue + padding,
        },
      },
    },
  })
  console.log(`MainEvaluationChart: Chart for ${pointName} drawn.`)
}

// 监听 props.device 变化时重新绘制图表
watch(
  () => props.device,
  async (newDevice) => {
    console.log(`MainEvaluationChart: Device prop changed to: ${newDevice}.`)
    if (newDevice) {
      // 只有当 newDevice 有效时才尝试绘制
      console.log(`MainEvaluationChart: Redrawing chart for device: ${newDevice}.`)
      // 使用 nextTick 确保 DOM 已经更新，尽管 canvas 不会被 v-if/v-show 切换，
      // 但确保在其他潜在 DOM 变动后 Chart.js 能找到 Canvas。
      await nextTick()
      drawMainEvaluationChart()
    } else {
      console.warn('MainEvaluationChart: Device prop is empty or invalid, skipping chart redraw.')
      destroyChart() // 清理旧图表
    }
  },
  { immediate: true },
) // immediate: true 确保在组件初始化时立即运行一次

// 组件挂载时触发 initial fetch and draw
onMounted(() => {
  // onMounted时不需要直接调用 drawMainEvaluationChart()，
  // 因为 watch(props.device, { immediate: true }) 已经处理了首次加载。
})

// 组件卸载时销毁图表实例，防止内存泄漏
onUnmounted(() => {
  destroyChart()
})
</script>
